from pyeasyaccept.result.Result import Result
from pyeasyaccept.commom.Configuration import Configuration

class ExpectErrorCommand:
    """
    It executes the given command (usually an external command) and checks if an
    exception was thrown. If an axception was thrown, Python EasyAccept compares the
    <error message> expected with the exception message. If those messages are identical,
    it returns a result with sucess message; otherwise, it returns a result with an erros message,
    describing that the error expected did not occur. 
     
    @author: Gustavo Pereira
    """
    
    def execute(self, script, parsedLine):
        """
        This method executes the Expect Error command
        """        
        if(parsedLine.getNumberOfParameters() < 3):
            raise Exception("ExpectError command syntax is: 'errorExpected expectedError apCommand arg1 arg2 ... argN'")

        excpectedErrorMessage = parsedLine.getParameter(1)
        apCommand = parsedLine.getParameter(2)
        
        if(self.hasParameters(parsedLine)):
            parameters = parsedLine.subLine(3)
        else:
            parameters = []    
        
        
        exceptionMessage = None
        exception = None
        appResult = None
        hasError = False
        try:
            appResult = script.execute(apCommand, parameters)
        except Exception, e:
            exception = e
            exceptionMessage = str(e) 
            hasError = True

 
        if(excpectedErrorMessage == str(exceptionMessage)):
            result = Result(parsedLine, Configuration.SUCCESS_CODE, exceptionMessage)
            result.addException(exception, exceptionMessage)
            return result
        else:
            if(hasError):
                result = Result(parsedLine, Configuration.ERROR_CODE, exceptionMessage)      
                result.addException(exception, "Exception message expected: '" + str(excpectedErrorMessage) + "' But got: '" + str(exceptionMessage)+ "'")
                return result

            else:            
                result = Result(parsedLine, Configuration.ERROR_CODE, appResult)      
                result.addException(exception, "An exception was expected, but not exception occurred.")
                return result
    

    def hasParameters(self, parsedLine):
        """
        This method informs if a script line has parameters or not
        @param parsedLine: the script line
        """
        return parsedLine.getNumberOfParameters() > 3
    
    def getParametersNames(self):
        return ["errorExpected"]
        
        
        